package com.blue.gateway.paycore.wxpay.pay;

import com.blue.gateway.common.Request;
import com.blue.gateway.config.BaseChannelConfig;
import com.blue.gateway.dto.Result;
import com.blue.gateway.enums.PayChannelEnum;
import com.blue.gateway.utils.BigDecimalUtil;
import com.blue.gateway.utils.RandomUtil;
import com.blue.gateway.utils.http.HttpClientsUtil;
import com.blue.gateway.utils.sign.WxPaySignature;
import com.blue.gateway.annotation.Channel;
import com.blue.gateway.common.request.PayRequest;
import com.blue.gateway.config.WxConfig;
import com.blue.gateway.paycore.wxpay.WxPayConstants;
import com.blue.gateway.enums.ServiceChannelEnum;
import com.blue.gateway.utils.XmlUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author xiaoyiming
 * @date 2020/5/3 19:15
 * @depiction 微信支付接口
 * APP支付:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
 */
@Slf4j
@Channel(PayChannel = PayChannelEnum.WX_APP, ServiceChannel = ServiceChannelEnum.PAY)
public class WxPayAppService extends WxPayService {

    @Override
    public Result validate(Request request) {
        return super.validate(request);
    }


    @Override
    public BaseChannelConfig getConfig(Request request) {
        return super.getConfig(request);
    }

    @Override
    public String generateParams(Request request, BaseChannelConfig channelConfig) {
        PayRequest payRequest = (PayRequest) request;
        WxConfig wxConfig = (WxConfig) channelConfig;

        SortedMap<String, String> params = new TreeMap<>();
        params.put("appid", wxConfig.getAppId());
        params.put("mch_id", wxConfig.getMchId());
        params.put("nonce_str", RandomUtil.getRandomStr());
        params.put("body", payRequest.getSubject());
        params.put("out_trade_no", payRequest.getOutTradeNo());
        params.put("total_fee", BigDecimalUtil.toUnitFen(payRequest.getTotalAmount()));
        params.put("spbill_create_ip", payRequest.getSpbillCreateIp());
        params.put("notify_url", payRequest.getNotifyUrl());
        params.put("trade_type", WxPayConstants.TRADE_TYPE_APP);

        String sign = WxPaySignature.sign(params, wxConfig.getParterKey());
        params.put("sign", sign);
        return XmlUtil.mapToXML(params);
    }

    @Override
    public String execute(String requestParams, BaseChannelConfig channelConfig) {
        // 发送请求
        String executeResult = null;
        try {
            executeResult = HttpClientsUtil.httpClientPost(WxPayConstants.WX_PAY_GATEWAY, requestParams);
        } catch (Exception e) {
            // do nothing
        }
        return executeResult;
    }

    @Override
    public Result analysisResult(String executeResult) {
        return super.analysisResult(executeResult);
    }
}
